<template>
  <textarea v-model="textRef"></textarea>
  <div>
    <highlightjs language="dart" :code="codeRef" />
  </div>
</template>

<script setup>
import { computed, shallowRef, watch } from 'vue';

/** @type {import('vue').Ref<string>} */
const textRef = shallowRef(localStorage.getItem("flutter-ui-prop") || '');

function toHump(name) {
  return name.replace(/\-(\w)/g, function (all, letter) {
    return letter.toUpperCase();
  });
}

watch(() => textRef.value, (text, old) => {
  if (text) localStorage.setItem("flutter-ui-prop", text);
}, { immediate: true });

const codeRef = computed(() => {
  const text = textRef.value;
  if (!text) return "";

  const props = [];
  const params = [];
  const table = document.createElement('table');
  table.innerHTML = text;
  console.log(table);
  [...table.querySelectorAll("tr")].forEach(tr => {
    console.log(tr);
    let [key, desc, type, value] = [...tr.querySelectorAll("td")].map(d => d.innerText);
    if (type.includes("string")) type = "String";
    else if (type.includes("boolean")) type = "bool";
    else if (type.includes("number")) type = "double";
    else type = "String"

    if (key == 'is-link') key = "linkable";
    key = toHump(key);

    if (value == '-' || value == 'null') value = '';

    const defaultValue = value ? `(默认: ${value})` : '';

    props.push(`  /// props - ${desc}${defaultValue}\n  final ${type}${value ? '' : '?'} ${key};`)

    if (!value) {
      params.push(`    this.${key},`)
    }
    else {
      if (type != 'double' && type != 'bool') value = JSON.stringify(value);
      params.push(`    this.${key} = ${value},`)
    }
  })

  return [
    props.join("\n"),
    '\n',
    params.join("\n"),
  ].join("\n");
});
</script>